package online.foxnull2.foxmall.ware.controller;

import online.foxnull2.common.exception.BizCodeEnum;
import online.foxnull2.common.utils.R;
import online.foxnull2.foxmall.ware.entity.WareSkuEntity;
import online.foxnull2.foxmall.ware.exception.StockInsufficientException;
import online.foxnull2.foxmall.ware.service.WareSkuService;
import online.foxnull2.foxmall.ware.utils.PageUtils;
import online.foxnull2.foxmall.ware.vo.wareSkuLock.WareSkuLockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 商品库存
 *
 * @author foxnull2
 */
@RestController
@RequestMapping("ware/waresku")
public class WareSkuController {

    private final WareSkuService wareSkuService;

    @Autowired
    public WareSkuController(WareSkuService wareSkuService) {
        this.wareSkuService = wareSkuService;
    }

    @PostMapping("/lock/order/sku")
    public R orderSkuLockStock(@RequestBody WareSkuLockVo wareSkuLockVo) {
        try {
            wareSkuService.orderSkuLockStock(wareSkuLockVo);
            return R.ok();
        } catch (StockInsufficientException e) {
            return R.error(BizCodeEnum.STOCK_INSUFFICIENT_EXCEPTION.getCode(),
                    BizCodeEnum.STOCK_INSUFFICIENT_EXCEPTION.getMsg());
        }
    }

    @PostMapping("/hasstock")
    public Set<Long> getSkuHasStock(@RequestBody List<Long> skuIds) {
        return wareSkuService.getSkuHasStock(skuIds);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = wareSkuService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        WareSkuEntity wareSku = wareSkuService.getById(id);

        return R.ok().put("wareSku", wareSku);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.save(wareSku);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.updateById(wareSku);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        wareSkuService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
